<?php

namespace page\models;

use Yii;

/**
 * This is the model class for table "menu".
 *
 * @property integer $id Menu id(autoincrement)
 * @property string $name Menu name
 * @property integer $parent Menu parent
 * @property string $route Route for this menu
 * @property integer $order Menu order
 * @property string $icon Extra information for this menu
 *
 * @property Menu $menuParent Menu parent
 * @property Menu[] $menus Menu children
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 */
class Directory extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%directory}}';
    }

    /**
     * @inheritdoc
     */
    public static function getDb()
    {
        return Yii::$app->getDb();
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['name', 'match', 'pattern' => '/^\w+$/i', 'message' => '只能包含字母数字下划线等字符'],
            [['parent_id',], 'required'],
            [['parent_id',], 'integer'],
            [['summary', 'path',], 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'summary' => '摘要',
            'parent_id' => '父目录',
            'path' => '目录层级路径',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'admin_id' => '账户ID',
        ];
    }

    public function beforeValidate(){
        if($this->getIsNewRecord()) {
            $this->create_time = time();
            $this->path = '';
        }
        $this->update_time = time();
        $this->admin_id = Yii::$app->user->id;
        return true;
    }

    public function getRealpath($path = '') {
        $realpath = '/';
        if($path) {
            $paths = explode(',', $path);
            if($paths) {
                foreach($paths as $id) {
                    if($model = self::findOne($id)) {
                        $realpath .= $model->name . '/';
                    }
                }
            }
        }
        return $realpath;
    }

    public function dropDown(){
        $dataList = [0 => '顶级'];
        $data = self::find(['select' =>array('id','path')])->asArray()->all();
        if($data) {
            foreach($data as $row) {
                $dataList[$row['id']] = $this->getRealpath($row['path']);
            }
        }
        return $dataList;
    }

    public function updatePath($directory = null){
        if($directory->parent_id) {
            $parentDirectory = self::findOne($directory->parent_id);
            $directory->path = $parentDirectory->path . ',' . $directory->id;
        } else {
            $directory->path = $directory->id;
        }
        return $directory->save(false);
    }

}